package dataMode;

import java.io.UnsupportedEncodingException;

public class ModeDetection {

	/*Teste la chaine a convertir pour en trouver le mode*/
	public static int testMode(String s) {
		if(isNumber(s))
			return QRData.MODE_NUMERIC;
		else if(isAlphaNum(s))
			return QRData.MODE_ALPHANUMERIC;
		else if(isKanji(s))
			return QRData.MODE_KANJI;
		else
			return QRData.MODE_BINARY;
	}
	
	/*
	 * Verifie si la chaine entr�e est un bit
	 */
	private static boolean isBit(String s) {
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (!('0' <= c && c <= '1') ) {
				return false;
			}
		}
		return true;
	}
	
	/*
	 * Verifie si la chaine entr�e est un nombre
	 */
	private static boolean isNumber(String s) {
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (!('0' <= c && c <= '9') ) {
				return false;
			}
		}
		return true;
	}

	/*
	 * Verifie si la chaine entr�e est alphanumerique
	 */
	private static boolean isAlphaNum(String s) {
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (!('0' <= c && c <= '9') && !('A' <= c && c <= 'Z') && " $%*+-./:".indexOf(c) == -1) {
				return false;
			}
		}
		return true;
	}

	/*
	 * Verifie si la chaine entr�e est de type kanji (Caract�res chinois)
	 */
	private static boolean isKanji(String s) {

		try {

			byte[] data = s.getBytes("SJIS");

			int i = 0;

			while (i + 1 < data.length) {
				
				int c = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]);

				if (!(0x8140 <= c && c <= 0x9FFC) && !(0xE040 <= c && c <= 0xEBBF) ) {
					return false;
				}
				
				i += 2;
			}

			if (i < data.length) {
				return false;
			}
			
			return true;

		} catch(UnsupportedEncodingException e) {
			throw new Error(e.getMessage() );
		}
	}
}
